package com.wn.EDI.action;

import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionSupport;
import com.wn.EDI.bean.DatEntityMo;
import com.wn.EDI.bean.DatEntityMt;
import com.wn.EDI.bean.DatEntityMth;
import com.wn.EDI.service.DatDumpService;
import com.wn.EDI.util.DatDumpModes;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONObject;
import org.apache.struts2.ServletActionContext;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
import org.springframework.stereotype.Controller;

@Controller
public class DatDumpAction extends ActionSupport
{
  private static final long serialVersionUID = -30244539436084234L;

  @Resource
  DatDumpService datDumpService;
  private String id;
  private String internal;
  private String cust;
  private String type;
  private int ifTrial;
  private String[] boxIds;
  private Gson gson = new Gson();

  private JSONObject jsonObj = new JSONObject();

  public String searchBoxId() {
    List bIds = this.datDumpService.searchBoxIdDistinct(this.id, 
      this.internal, this.cust);
    this.jsonObj.put("grid", bIds);
    return "ajax";
  }

  public String createDir() {
    HttpServletRequest req = ServletActionContext.getRequest();
    String path = req.getSession().getServletContext().getRealPath("/");
    SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
    Calendar cal = Calendar.getInstance();
    String rootStr = path + "EDI_fileExport" + File.separator + 
      fmt.format(cal.getTime());
    File rootDir = new File(rootStr);
    if (!rootDir.exists()) {
      rootDir.mkdirs();
    }
    cal.set(5, cal.get(5) - 2);

    String oldStr = path + "EDI_fileExport" + File.separator + 
      fmt.format(cal.getTime());
    File oldDir = new File(oldStr);
    if (oldDir.exists()) {
      oldDir.delete();
    }
    this.jsonObj.put("dir", rootStr);

    return "ajax";
  }

  public String createFile() {
    HttpServletRequest req = ServletActionContext.getRequest();

    String path = req.getSession().getServletContext().getRealPath("/");

    File rootDir = new File(path + "EDI_fileExport");
    if (!rootDir.exists()) {
      rootDir.mkdirs();
    }
    DatDumpModes dmode = new DatDumpModes();

    if (this.type.equals("1")) {
      List prdInfo = this.datDumpService.findByIdModeOne(this.id);
      String fileName = ((DatEntityMo)prdInfo.get(0)).getInboxId() + 
        ".dat";
      String filePath = path + "EDI_fileExport" + File.separator + 
        fileName;
      boolean flag = dmode.datDumpMo(prdInfo, this.ifTrial, filePath);

      if (flag) {
        this.jsonObj.put("msg", "success");
        this.jsonObj.put("name", fileName);
      } else {
        this.jsonObj.put("msg", "error");
        this.jsonObj.put("name", "");
      }
    } else if (this.type.equals("2")) {
      List datMtList = this.datDumpService.findByIdModeTwo(this.id);
      String fileName = ((DatEntityMt)datMtList.get(0)).getInboxId();
      if ((fileName == null) || ("".equals(fileName))) {
        fileName = this.id;
      }
      fileName = fileName + ".dat";
      String filePath = path + "EDI_fileExport" + File.separator + 
        fileName;
      boolean flag = dmode.datDumpMt(datMtList, filePath);

      if (flag) {
        this.jsonObj.put("msg", "success");
        this.jsonObj.put("name", fileName);
      } else {
        this.jsonObj.put("msg", "error");
        this.jsonObj.put("name", "");
      }
    } else if (this.type.equals("3")) {
      List datMthList = this.datDumpService.findByIdModeThree(this.id);

      int fullQty = this.datDumpService.getFullQty(this.id);
      String fileName = ((DatEntityMth)datMthList.get(0)).getPpboxId();
      if ((fileName == null) || ("".equals(fileName))) {
        fileName = this.id;
      }
      if ("071".equals(this.cust)){
        fileName = "WHTM_BH_" + fileName + "_" + 
          ((DatEntityMth)datMthList.get(0)).getProduct().substring(2, 5) + "_" + 
          ((DatEntityMth)datMthList.get(0)).getShipDate() + 
          ".xml";
      } else if ("168".equals(this.cust) || "169".equals(this.cust)) {
        fileName = this.id + "_" + ((DatEntityMth)datMthList.get(0)).getShipDate() + 
            ".xml";
      } else {
        fileName = "CDTM_BH_" + fileName + "_" + 
          ((DatEntityMth)datMthList.get(0)).getProduct().substring(2, 5) + "_" + 
          ((DatEntityMth)datMthList.get(0)).getShipDate() + 
          ".xml";
      }

      String filePath = path + "EDI_fileExport" + File.separator + 
        fileName;
      boolean flag = dmode.datDumpMth(this.id, this.cust, datMthList, filePath, fullQty);

      if (flag) {
        this.jsonObj.put("msg", "success");
        this.jsonObj.put("name", fileName);
      } else {
        this.jsonObj.put("msg", "error");
        this.jsonObj.put("name", "");
      }
    }
    return "ajax";
  }

  public String download() {
    HttpServletRequest req = ServletActionContext.getRequest();
    HttpServletResponse res = ServletActionContext.getResponse();
    String path = req.getSession().getServletContext().getRealPath("/");
    File rootDir = new File(path + "EDI_fileExport");
    if (this.boxIds.length == 1) {
      try {
        File curFile = new File(rootDir, this.boxIds[0]);
        if (curFile.exists()) {
          BufferedInputStream fis = new BufferedInputStream(
            new FileInputStream(curFile));
          byte[] buffer = new byte[2048];

          res.reset();
          res.setHeader("Content-disposition", "attachment;filename=" + 
            new String(curFile.getName().replace(" ", "")
            .getBytes(), "ISO8859-1"));
          res.setContentLength((int)curFile.length());
          res.setContentType("application/octet-stream");

          BufferedOutputStream out = new BufferedOutputStream(res
            .getOutputStream());
          int len;
          while ((len = fis.read(buffer)) > 0)
          {
            //int len;
            out.write(buffer, 0, len);
          }
          fis.close();
          out.flush();
          out.close();
          return null;
        }
        return "error";
      } catch (Exception e) {
        return "error";
      }
    }

    if (this.boxIds.length > 1) {
      String zipFileName = this.boxIds[0] + "等" + this.boxIds.length + 
        "个文件.zip";
      try {
        res.setHeader("Content-disposition", "attachment;filename=" + 
          new String(zipFileName.replace(" ", "").getBytes(), 
          "ISO8859-1"));
        res.setContentType("application/octet-stream");
        ZipOutputStream zipOut = new ZipOutputStream(
          new BufferedOutputStream(res.getOutputStream()));
        zipOut.setEncoding("GBK");

        for (int i = 0; i < this.boxIds.length; i++) {
          File outFile = new File(rootDir, this.boxIds[i]);
          if (outFile.exists()) {
            BufferedInputStream bis = new BufferedInputStream(
              new FileInputStream(outFile));
            zipOut.putNextEntry(new ZipEntry(outFile.getName()));
            byte[] buffer = new byte[2048];
            int len;
            while ((len = bis.read(buffer)) > 0)
            {
              //int len;
              zipOut.write(buffer, 0, len);
            }
            bis.close();
          }
        }
        zipOut.flush();
        zipOut.close();
      } catch (IOException e) {
        return "error";
      }
    }
    return null;
  }

  public String getId() {
    return this.id;
  }

  public void setId(String id) {
    this.id = id;
  }

  public String getInternal() {
    return this.internal;
  }

  public void setInternal(String internal) {
    this.internal = internal;
  }

  public int getIfTrial() {
    return this.ifTrial;
  }

  public void setIfTrial(int ifTrial) {
    this.ifTrial = ifTrial;
  }

  public String getCust() {
    return this.cust;
  }

  public void setCust(String cust) {
    this.cust = cust;
  }

  public Gson getGson() {
    return this.gson;
  }

  public void setGson(Gson gson) {
    this.gson = gson;
  }

  public JSONObject getJsonObj() {
    return this.jsonObj;
  }

  public void setJsonObj(JSONObject json) {
    this.jsonObj = json;
  }

  public DatDumpService getDatDumpService() {
    return this.datDumpService;
  }

  public void setDatDumpService(DatDumpService service) {
    this.datDumpService = service;
  }

  public String getType() {
    return this.type;
  }

  public void setType(String type) {
    this.type = type;
  }

  public String[] getBoxIds() {
    return this.boxIds;
  }

  public void setBoxIds(String[] boxIds) {
    this.boxIds = boxIds;
  }
}